package cn.school.mybaits.Server;

import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.SqlSession;

import cn.school.mybaits.Dao.StudentDao;
import cn.school.mybaits.entity.Student;
import cn.school.mybaits.xml.MyBatisUtil;

public class StudentServer {
	// 查找所有学生
	public List<Student> search(Map<String, Object> map, int pageNo, int pageSize, String q) {
		SqlSession session = MyBatisUtil.get();
		try {
			StudentDao studentDao = session.getMapper(StudentDao.class);
			List<Student> list = studentDao.search(map, pageNo, pageSize, q);
			return list;
		} finally {
			MyBatisUtil.close(session);
		}
	}

	// 增加学生
	public int add(Student s) {
		SqlSession session = MyBatisUtil.get();
		try {
			StudentDao studentDao = session.getMapper(StudentDao.class);
			int num = studentDao.add(s);
			return num;
		} finally {
			MyBatisUtil.close(session);
		}
	}

	// 修改学生
	public int update(Map<String, Object> map) {
		SqlSession session = MyBatisUtil.get();
		try {
			StudentDao studentDao = session.getMapper(StudentDao.class);
			int num = studentDao.update(map);
			return num;
		} finally {
			MyBatisUtil.close(session);
		}
	}

	// 获得页数
	public int findTotal(Map<String, Object> map, int pageSize) {
		SqlSession session = MyBatisUtil.get();
		try {
			StudentDao studentDao = session.getMapper(StudentDao.class);
			int num = studentDao.findTotal(map);
			return num / pageSize + (num % pageSize == 0 ? 0 : 1);// 返回总页数
		} finally {
			MyBatisUtil.close(session);
		}
	}

	// 查询某位学生
	public Student get(long num) {
		SqlSession session = MyBatisUtil.get();
		try {
			StudentDao studentDao = session.getMapper(StudentDao.class);
			Student student = studentDao.get(num);
			return student;
		} finally {
			MyBatisUtil.close(session);
		}
	}

	// 删除学生
	public int delete(long num) {
		SqlSession session = MyBatisUtil.get();
		try {
			StudentDao studentDao = session.getMapper(StudentDao.class);
			int number = studentDao.delete(num);
			return number;
		} finally {
			MyBatisUtil.close(session);
		}
	}

	// 验证微信不能重复
	public boolean cheakWechat(String wechat) {
		SqlSession session = MyBatisUtil.get();
		try {
			StudentDao studentDao = session.getMapper(StudentDao.class);
			int number = studentDao.cheakWechat(wechat);
			return number > 0;
		} finally {
			MyBatisUtil.close(session);
		}
	}
}
